<!-- 检查项目处方 -->
<template>
  <div>
    <el-dialog title="处方" v-model="innerVisible">
      <div v-loading="addLoading"
        element-loading-text="正在提交服务器中">
        <table style="width:100%;">
          <tr>
            <td>处方名:</td>
            <td colspan=3>
              <el-input size="mini" placeholder="病 历 名 称 或 类 别" v-model="reports.header.name"></el-input>
            </td>
            <td>诊断类型:</td>
            <td>
              <el-select v-model="reports.header.diagnostic_type" style="width:6em;">
                <el-option label="初诊" value="0"></el-option>
                <el-option label="复诊" value="1"></el-option>
              </el-select>
            </td>
          </tr>
          <tr>
            <td>医生:</td><td>{{ reports.header.doctor }}</td>
            <td>科别:</td><td>{{ reports.header.department }}</td>
            <td>医疗证:</td><td>{{ reports.header.doctor_licence }}</td>
            <td>时间:</td><td>{{ reports.header.d_time }}</td>
          </tr>
          <tr>
            <td>姓名:</td><td>{{ reports.header.partner_name }}</td>
            <td>性别:</td>
            <td>
              <div v-if="reports.header.sex == 'm'">男</div>
              <div v-if="reports.header.sex == 'w'">女</div>
            </td>
            <td>年龄:</td><td>{{ reports.header.age }}</td>
            <td>出生日期:</td><td>{{ reports.header.birthday }}</td>
          </tr>
          <tr>
            <td>联系电话:</td><td>{{ reports.header.phone }}</td>
            <td>地址:</td><td colspan=2>{{ reports.header.street }}</td>
            <td>过敏史:</td><td colspan=2>{{ reports.header.allergic_note }}</td>
          </tr>
          <tr>
            <td>诊断:</td>
            <td colspan=7>
              <el-input type="textarea" v-model="reports.header.diagnose"></el-input>
            </td>
          </tr>
          <tr>
            <td>医嘱:</td>
            <td colspan=7>
              <el-input type="textarea" v-model="reports.header.doctor_advice"></el-input>
            </td>
          </tr>
        </table>
        <table class="addDrug">
          <tr>
            <th>序号</th><th>药品名称</th><th>次数</th><th>单价</th><th>部位</th><th>操作</th>
          </tr>
          <tr v-for="row in reports.detail">
            <td>{{ row.index }}</td>
            <td>
              <el-autocomplete
                v-model="row.name"
                size="small"
                :fetch-suggestions="querySearchDrug"
                placeholder="检查项目搜索"
                :trigger-on-focus="false"
                @select="handleSelectDrug">
              </el-autocomplete>
            </td>
            <td style="width: 100px;"><input style="width: 100px;" v-model="row.product_uom_qty"></input></td>
            <td style="width: 100px;"><input style="width: 100px;" v-model="row.price_unit"></input></td>
            <td style="width: 140px;"><input style="width: 140px;" v-model="row.usage"></input></td>
            <td>
              <el-button icon="delete" size="small" @click.native="deleteLine(row.index)"></el-button>
            </td>
          </tr>
        </table>
        <span class="dialog-footer">
          <el-button type="primary" @click.native="IncreaseLine">增加药品</el-button>
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click.native="innerVisible=false">取 消</el-button>
        <el-button type="primary" @click.native="addReport(reports)">{{ buttonName }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import '../../assets/scripts/TimeFormat.js'
export default {
  data() {
    return {
      reports: {
        header: {
          id: 0,
          name: '',
          prescription_type: '2',
          doctor: '医生类',
          department: '科别类',
          doctor_licence: '123456789',
          d_time: null,
          partner_id: '',
          partner_name: '',
          sex: '',
          age: '',
          birthday: '',
          phone: '',
          street: '',
          allergic_note: '',
          diagnostic_type: '0',
          diagnose: '',
          doctor_advice: ''
        },
        detail: [
          { "index": 1,
            "product_id": "",
            "name": "",
            "content_unit": "",
            "drug_spec": "",
            "dosis": "",
            "usage": "",
            "times": "",
            "day": "",
            "product_uom_qty": 1,
            "product_uom": "",
            "count_unit": [],
            "price_unit": "",
            "use_level": ""
          }
        ]
      },
      innerVisible: false,
      currentTime: null,
      buttonName: '',
      addLoading: false,
      allergics: []
    }
  },
  props: {
    judge: null,
    partnerId: null,
    Visible: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    addReport(reports) {
      this.addLoading = true
      var str = JSON.stringify(reports)
      var data = JSON.parse(str)
      if (this.judge == 'add') {
        this.$http.post('/api/prescriptions/augment', data).then((response) => {
          this.addLoading = false
          this.innerVisible = false
          this.$message({
            showClose: true,
            message: '添加成功',
            type: 'success'
          })
        }, (response) => {
          this.addLoading = false
          this.$message({
            showClose: true,
            message: '服务器连接失败',
            type: 'error'
          })
        })
      }
      if (this.judge == 'detailed') {
        if (data.header.state == 'sale') {
          this.$http.put('/api/prescriptions/up', data).then((response) => {
            this.addLoading = false
            this.innerVisible = false
            this.$message({
              showClose: true,
              message: '成功修改',
              type: 'success'
            })
          }, (response) => {
            this.addLoading = false
            this.$message({
              showClose: true,
              message: '服务器连接失败',
              type: 'error'
            })
          })
        } else {
          this.addLoading = false
          this.$alert('该处方交易已完成，请勿修改', '提示', {
            type: 'warning',
            callback: action => {
              this.reports = JSON.parse(this.cacheReports)
            }
          })
        }
      }
    },
    querySearchDrug(queryString, funcd) {/*查找药品*/
      if (queryString == '') {
        funcd()
      }
      else {
        this.$http.get('/api/drugs/'+queryString+'/1').then(function (response) {
          let data = []
          let datas = response.data.data
          for (let i = 0; i < datas.length; i++) {
            data[i] = { 'value': datas[i].name, 'id': datas[i].id, 'allergic_history': datas[i].allergic_history }
          }
          if (data.length > 0) {
            funcd(data)  
          } else {
            data[0] = { 'value': '' }
            funcd(data)
          }          
        }, (response) => {
          this.$message({
            showClose: true,
            message: '服务器连接失败',
            type: 'error'
          })
          funcd()
        })      
      }
    },
    handleSelectDrug(val) {
      if (this.allergics[0].drug_allergic == '无') {
        this.addDrugInfo(val)
      } else {
        let vm = this
        let VerifyDrug = this.allergics.map(function(obj) {
          if (obj.key == 1 && obj.drug_id == val.id) {
            vm.$alert('该患者'+val.value+'过敏，请不要开此药', '提示', { type: 'warning' })
            return false
          } else if (obj.key == 2 && obj.drug_id == val.allergic_history[0]) {
            vm.$alert('该患者'+val.allergic_history[1]+'过敏，请不要开此药', '提示', { type: 'warning' })
            return false
          } else {
            return true
          }
        }).indexOf(false)
        if (VerifyDrug == -1) {
          this.addDrugInfo(val)
        } else {
          for (let i = 0; i < this.reports.detail.length; i++) {
            if (this.reports.detail[i].name == val.value) {
              this.reports.detail[i].name = ''
            }
          }
        }
      }
    },
    // 用ID查询药品
    addDrugInfo(val) {
      this.$http.get('/api/drugs/id/'+val.id).then(function (response) {
        var data = response.data
        for (let i = 0; i < this.reports.detail.length; i++) {
          if (this.reports.detail[i].name == val.value) {
            this.reports.detail[i].product_id = data.id
            this.reports.detail[i].price_unit = data.small_price
            this.reports.detail[i].product_uom = data.small_unit[0]
            this.reports.detail[i].usage = data.usage[1]
          }
        }
      }, (response) => {
        this.$message({
          showClose: true,
          message: '服务器连接失败',
          type: 'error'
        })
      })
    },
    IncreaseLine() { /*增加行*/
      this.reports.detail.push({ 
        "index": 1,
        "product_id": "",
        "name": "",
        "content_unit": "",
        "drug_spec": "",
        "dosis": "",
        "usage": "",
        "times": "",
        "day": "",
        "product_uom_qty": 1,
        "product_uom": "",
        "count_unit": [],
        "price_unit": "",
        "use_level": ""
      })
      this.SinceGrowth()
    },
    deleteLine(index) { /*删除行*/
      this.reports.detail.splice(index-1, 1)
      this.SinceGrowth()
    },
    SinceGrowth() { /*索引*/
      for(let i=0;i<this.reports.detail.length;i++) {
        this.reports.detail[i].index=i+1 
      }  
    }
  },
  watch: {
    Visible: function (val, oldVal) {
      this.innerVisible = val
    },
    innerVisible: function (val, oldVal) {
      if (val) {
        let vm = this
        if (vm.judge == 'add') {
          vm.buttonName = '添加'
          vm.$http.get('/api/patients/'+vm.partnerId).then(function(response) {
            let date = new Date(response.headers.map.date[0])
            let data = response.data
            vm.reports.header.d_time = date.Format("yyyy-MM-dd")
            vm.reports.header.partner_id = data.base.id
            vm.reports.header.partner_name = data.base.name
            vm.reports.header.sex = data.base.sex
            vm.reports.header.age = data.base.age
            vm.reports.header.birthday = data.base.birthday
            vm.reports.header.phone = data.base.phone
            vm.reports.header.street = data.base.street
            vm.reports.header.allergic_note = data.allergic.map(function(obj) {
                return obj.drug_allergic
            }).join(', ')
            vm.allergics = data.allergic.map(function(obj) {
              return { key: obj.key, drug_id: obj.drug_id, drug_allergic: obj.drug_allergic }
            })
          }, (response) => {
            vm.$message({
              showClose: true,
              message: '服务器连接失败',
              type: 'error'
            })
          })
        }
        if (vm.judge == 'detailed') {
          vm.buttonName = '修改'
          vm.$http.get('/api/prescriptions/'+vm.partnerId).then(function (response) {
            let data = response.data
            vm.reports = Object.assign({},data)
            vm.reports.header.partner_id = data.header.partner_id[0]
            for (let i=0; i<data.detail.length; i++) {
              vm.reports.detail[i].index = i+1
              vm.reports.detail[i].product_id = data.detail[i].product_id[0]
              vm.reports.detail[i].order_id = data.detail[i].order_id[0]
              vm.reports.detail[i].product_uom = data.detail[i].product_uom[0]
            }
            vm.allergics = data.allergic.map(function(obj) {
              return { key: obj.key, drug_id: obj.drug_id, drug_allergic: obj.drug_allergic }
            })
            vm.cacheReports = JSON.stringify(vm.reports)
          }, (response) => {
            vm.$message({
              showClose: true,
              message: '服务器连接失败',
              type: 'error'
            })
          })
        }
      } else {
        this.$emit('fromson')
      }
    }
  }
}
</script>